Skip to content

Fix KeyNotFoundException on missing correlation ID header in token responses#5757

Closed
Copilot wants to merge 2 commits into
mainfrom
copilot/fix-managed-identity-header-access
Closed

Fix KeyNotFoundException on missing correlation ID header in token responses#5757
Copilot wants to merge 2 commits into
mainfrom
copilot/fix-managed-identity-header-access

Conversation

Copy link
Copy Markdown
Contributor

Copilot AI commented Feb 12, 2026

Changes proposed in this request

Container Apps and other environments may omit the client-request-id correlation ID header in OAuth2 token responses. OAuth2Client.VerifyCorrelationIdHeaderInResponse used unsafe dictionary indexing that throws KeyNotFoundException when the header is absent.

Clarification on scope: Issue reported as "ManagedIdentityCredential failing" but Managed Identity flow doesn't use OAuth2Client - it has a separate code path through AbstractManagedIdentity.AuthenticateAsync() that already uses safe patterns. The error occurs in OAuth2/OIDC flows (confidential client, public client, etc.) running in Container Apps environments.

Changed:

  • src/client/Microsoft.Identity.Client/OAuth2/OAuth2Client.cs: VerifyCorrelationIdHeaderInResponse now uses TryGetValue() with null/empty checks instead of direct dictionary access

Before:

foreach (string responseHeaderKey in headers.Keys)
{
    string trimmedKey = responseHeaderKey.Trim();
    if (string.Compare(trimmedKey, OAuth2Header.CorrelationId, StringComparison.OrdinalIgnoreCase) == 0)
    {
        string correlationIdHeader = headers[trimmedKey].Trim();  // Throws if key not found
        // ... validation
    }
}

After:

foreach (string responseHeaderKey in headers.Keys)
{
    string trimmedKey = responseHeaderKey.Trim();
    if (string.Compare(trimmedKey, OAuth2Header.CorrelationId, StringComparison.OrdinalIgnoreCase) == 0)
    {
        if (headers.TryGetValue(responseHeaderKey, out string headerValue) && !string.IsNullOrEmpty(headerValue))
        {
            string correlationIdHeader = headerValue.Trim();
            // ... validation
        }
        break;
    }
}

Testing

Added CorrelationIdHeaderTests.cs with 5 test cases:

  • Header present with matching/mismatching correlation ID
  • Header missing (Container Apps scenario)
  • Empty header value
  • Case-insensitive matching
  • Multiple headers without correlation ID

All 25 existing OAuth2Tests pass.

Performance impact

None. TryGetValue is equivalent to dictionary indexing with existence check.

Documentation

  • All relevant documentation is updated.
Original prompt

Bug Fix: Safe Access to Response Headers Dictionary in Managed Identity Error Handling

Problem

When ManagedIdentityCredential authentication fails in Container Apps, the error message "The given key client-request-id was not present in the dictionary" is thrown because the code attempts to access the response headers dictionary without checking if the key exists first.

This occurs in the VerifyCorrelationIdHeaderInResponse method in OAuth2Client.cs which uses direct dictionary access headers[trimmedKey] without first verifying the key exists via ContainsKey().

Unlike App Services which include the "client-request-id" header in error responses, Container Apps may not include this header, causing a KeyNotFoundException.

Root Cause

In OAuth2Client.cs (line 372-385), the VerifyCorrelationIdHeaderInResponse method iterates through response headers and attempts to access the correlation ID header using direct dictionary indexing without checking if the key exists:

foreach (string responseHeaderKey in headers.Keys)
{
    string trimmedKey = responseHeaderKey.Trim();
    if (string.Compare(trimmedKey, OAuth2Header.CorrelationId, StringComparison.OrdinalIgnoreCase) == 0)
    {
        string correlationIdHeader = headers[trimmedKey].Trim();  // This can throw KeyNotFoundException
        // ...
    }
}

Solution

Wrap the dictionary access in a try-catch or use TryGetValue() method to safely handle cases where the header might not be present. This approach follows the pattern established in PR #5364.

Files to Modify

  1. src/client/Microsoft.Identity.Client/OAuth2/OAuth2Client.cs - Fix the unsafe dictionary access in VerifyCorrelationIdHeaderInResponse method

Tests to Add

Add unit tests in tests/Microsoft.Identity.Test.Unit/PublicApiTests/ExtraHttpHeadersTests.cs or create a new test file to verify:

  1. Normal case where correlation ID header is present
  2. Case where correlation ID header is missing (should not throw)
  3. Case where multiple headers are present but correlation ID is missing
  4. Managed Identity scenario with missing correlation ID header

This pull request was created from Copilot chat.


💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.

…nd add tests

Co-authored-by: gladjohn <90415114+gladjohn@users.noreply.github.com>
Copilot AI changed the title [WIP] Fix safe access to response headers in error handling Fix KeyNotFoundException on missing correlation ID header in managed identity responses Feb 12, 2026
Copilot AI requested a review from gladjohn February 12, 2026 00:40
@gladjohn gladjohn marked this pull request as ready for review February 12, 2026 01:31
@gladjohn gladjohn requested a review from a team as a code owner February 12, 2026 01:31
Copilot AI changed the title Fix KeyNotFoundException on missing correlation ID header in managed identity responses Fix KeyNotFoundException on missing correlation ID header in token responses Feb 12, 2026
@gladjohn gladjohn marked this pull request as draft February 12, 2026 01:41
@gladjohn gladjohn closed this Feb 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants